<?php
/**************************************************************************
	ESAM (EVE to SMF API Module)
	Copyright (C) 2009  Sasha J

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/

if (!defined('SMF')) die('Hacking attempt...');

include_once('Subs.php');
include_once('Subs-Members.php');
include_once('EveApi.php');

global $db_prefix;

function getEveModVersion() {
    return '1.0.7';
}

// Settings
function getEveSetting($name, $member_id = 'NULL') {
    global $db_prefix;
    $request = db_query("SELECT * FROM {$db_prefix}eve_settings WHERE
    NAME = '{$name}'".($member_id == 'NULL' ? "" : " AND ID_MEMBER = {$member_id}")." LIMIT 1", __FILE__, __LINE__);
    $value = 0; // 0 is allways default setting
    while($row = mysql_fetch_assoc($request)) {
        $value = $row['VALUE'];
    }
	mysql_free_result($request);
    return $value;
}
function saveEveSetting($name, $value, $member_id = 'NULL') {
    global $db_prefix;
    db_query("DELETE FROM {$db_prefix}eve_settings WHERE
    NAME = '{$name}'".($member_id == 'NULL' ? "" : " AND ID_MEMBER = {$member_id}"), __FILE__, __LINE__);
    db_query("INSERT INTO {$db_prefix}eve_settings (NAME, VALUE, ID_MEMBER) VALUES
    ('{$name}', {$value}, {$member_id})", __FILE__, __LINE__);
}

// User EVE data
function saveEveUserData($member_id, $user_id, $api_key) {
    global $db_prefix;
    db_query("DELETE FROM {$db_prefix}eve_api_keys
	WHERE ID_MEMBER = {$member_id}", __FILE__, __LINE__);
    db_query("
	INSERT INTO {$db_prefix}eve_api_keys
		(ID_MEMBER, USER_ID, API_KEY) VALUES ({$member_id}, '{$user_id}', '{$api_key}')", __FILE__, __LINE__);

}
function getEveUserData($member_id) {
    global $db_prefix;
    $request = db_query("SELECT * FROM {$db_prefix}eve_api_keys WHERE ID_MEMBER = {$member_id} LIMIT 1", __FILE__, __LINE__);
    $result = array();
    while($row = mysql_fetch_assoc($request)) {
       $result[] = $row;
    }
	mysql_free_result($request);
    return $result;
}
function deleteEveUserData($condition) {
    global $db_prefix;
    db_query("DELETE FROM {$db_prefix}eve_api_keys
	WHERE ID_MEMBER $condition", __FILE__, __LINE__);
    db_query("DELETE FROM {$db_prefix}eve_characters
	WHERE ID_MEMBER $condition", __FILE__, __LINE__);
}

// Characters
function removeEveCharacters($member_id) {
    global $db_prefix;
    db_query("
	DELETE FROM {$db_prefix}eve_characters
	WHERE ID_MEMBER = {$member_id}", __FILE__, __LINE__);
}

function saveEveCharacter($member_id, $char, $corp_id, $corp_name, $alliance_name) {
    global $db_prefix;
    $char = mysql_real_escape_string($char);
    $corp_name = mysql_real_escape_string($corp_name);
    $alliance_name = mysql_real_escape_string($alliance_name);
    db_query("
	INSERT INTO {$db_prefix}eve_characters
		(ID_MEMBER, EVE_CHAR_NAME, EVE_CORP_ID, EVE_CORP_NAME, EVE_ALLIANCE_NAME)
        VALUES ({$member_id}, '{$char}', {$corp_id}, '{$corp_name}', '{$alliance_name}')", __FILE__, __LINE__);
}

function getEveCharacters($member_id) {
    global $db_prefix;
    $request = db_query("
			SELECT *
			FROM {$db_prefix}eve_characters
			WHERE ID_MEMBER = '{$member_id}'", __FILE__, __LINE__);
    $result = array();
    while($row = mysql_fetch_assoc($request)) {
       $result[] = $row;
    }
	mysql_free_result($request);
    return $result;
}

function getSidebarEveCharactersText($member_id) {
    $chars = getEveCharacters($member_id);
    $text = '';
    foreach($chars as $k => $v) {
        $text .= '<strong>'.$v['EVE_CHAR_NAME'].'</strong><br />';
        $text .= $v['EVE_CORP_NAME'].'<br />';
        if($v['EVE_ALLIANCE_NAME'] != null) $text .= $v['EVE_ALLIANCE_NAME'].'<br />';
    }
    return $text;
}

function checkUserAndKey($user_id, $api_key) {
    global $db_prefix;
    if(getEveSetting('GLOBAL_REQUIRED_API') == 1) return true;
    // check user info
    $ea = new EveApi();
    $ea->setCredentials($user_id, $api_key);
    $data = $ea->getCharacters();
    if($ea->isError()) return false;
    return true;
}

function checkSameEveUserData($user_id, $api_key) {
    global $db_prefix;
    if(getEveSetting('GLOBAL_REQUIRED_API') == 1) return true;
    $request = db_query("
			SELECT *
			FROM {$db_prefix}eve_api_keys
			WHERE USER_ID = '{$user_id}' AND API_KEY = '{$api_key}'", __FILE__, __LINE__);
    if(mysql_num_rows($request) > 0) return false;
    return true;
}


function revalidateEveUsers() {
    global $db_prefix;
    $request = db_query("SELECT * FROM {$db_prefix}eve_api_keys", __FILE__, __LINE__);
    $result = array();
    while($row = mysql_fetch_assoc($request)) {
       $result[] = $row;
    }
	mysql_free_result($request);
    foreach($result as $key => $val) {
        checkEveUserRoles($val['ID_MEMBER']);
    }
}

function checkEveUserRoles($memberid) {
    global $db_prefix;
    $rules = getEveRules();
    // Find userid and api key for this member
    $request = db_query("
			SELECT *
			FROM {$db_prefix}eve_api_keys
			WHERE ID_MEMBER = '{$memberid}'", __FILE__, __LINE__);
    $uid = $akey = null;
    while($row = mysql_fetch_assoc($request)) {
       $uid = $row['USER_ID'];
       $akey = $row['API_KEY'];
    }
	mysql_free_result($request);
    if($uid == null) return;
    // download character list
    $ea = new EveApi();
    $ea->setCredentials($uid, $akey);
    $data = $ea->getCharacters();
    $ea->printErrors();
    if($ea->isError()) return;
    // scan characters
    removeEveCharacters($memberid);
    $xml = new SimpleXMLElement($data);
    foreach ($xml->result->rowset->row as $row) {
        foreach ($row->attributes() as $key => $val) {
            if($key == 'characterID') {
                $ea->setCredentials($uid, $akey, $val);
                $c = $ea->getCharacterSheet();
                if($ea->isError()) return;
                $cxml = new SimpleXMLElement($c);
                $char = $cxml->result->name;
                $corp_id = $cxml->result->corporationID;
                $alliance_id = getCorpAlliance($corp_id);
                $corp_name = mysql_escape_string((string) $cxml->result->corporationName);
                saveEveCharacter($memberid, $char, $corp_id, $corp_name, mysql_escape_string((string) getAllianceName($alliance_id)));
                // Corporation member?
                $mrequest = db_query("SELECT * FROM {$db_prefix}eve_rules WHERE EVE_ROLE = '' AND
                            (EVE_CORP_ID = '{$corp_id}')", __FILE__, __LINE__);
                while($drow = mysql_fetch_assoc($mrequest)) {
                    addEveMemberToGroup($memberid, $drow['ID_GROUP']);
                }
                // Alliance member?
                $mrequest = db_query("SELECT * FROM {$db_prefix}eve_rules WHERE EVE_ROLE = '' AND
                            (EVE_ALLIANCE_ID = '{$alliance_id}')", __FILE__, __LINE__);
                while($drow = mysql_fetch_assoc($mrequest)) {
                    addEveMemberToGroup($memberid, $drow['ID_GROUP']);
                }
                // scan director role
                $cresult = $cxml->xpath("//eveapi/result/rowset[@name='corporationRoles']");
                foreach ($cresult[0]->row as $crow) {
                    foreach ($crow->attributes() as $ckey => $cval) {
                        if($ckey == 'roleName' && $cval == 'roleDirector') {
                            $mrequest = db_query("SELECT * FROM {$db_prefix}eve_rules WHERE
                                 EVE_ROLE = 'roleDirector' AND
                                 (EVE_CORP_ID = '{$corp_id}' OR EVE_ALLIANCE_ID = '{$alliance_id}')", __FILE__, __LINE__);
                            while($drow = mysql_fetch_assoc($mrequest)) {
                                addEveMemberToGroup($memberid, $drow['ID_GROUP']);
                            }
                        }
                    }
                }
            }
		}
	}
}

// Corporations
function fillCorpsFromAlliance($alid) {
    global $db_prefix;
    // Delete those corporations
    db_query("DELETE FROM {$db_prefix}eve_corporations WHERE eve_alliance_id = '{$alid}'", __FILE__, __LINE__);
    $ea = new EveApi();
    $data = $ea->getAllianceList();
    $xml = new SimpleXMLElement($data);
    $result = $xml->xpath("//eveapi/result/rowset/row[@allianceID='" . $alid . "']/rowset");
    foreach ($result[0]->row as $row) {
        foreach ($row->attributes() as $key => $val) {
            if($key == 'corporationID') {
                $ea->setCredentials(null, null, null, $val);
                $cinfo = $ea->getCorporationInfo();
                $cx = new SimpleXMLElement($cinfo);
                $name = mysql_real_escape_string((string) $cx->result->corporationName);
                db_query("INSERT INTO {$db_prefix}eve_corporations (EVE_ID, EVE_NAME, EVE_ALLIANCE_ID) VALUES
                         ('{$cx->result->corporationID}','{$name}','{$alid}')", __FILE__, __NAME__);
            }
        }
    }
}

// Not used, only for corporations that are not member of any alliance
function addCorporation($name) {
    global $db_prefix;
    $name = mysql_real_escape_string($name);
    db_query("INSERT INTO {$db_prefix}eve_corporations (EVE_NAME) VALUES ('{$name}')", __FILE__, __NAME__);
}

function removeCorporation($id) {
    global $db_prefix;
    db_query("DELETE FROM {$db_prefix}eve_corporations WHERE EVE_ID = '{$id}'", __FILE__, __NAME__);
}

function getCorporations($alid) {
    global $db_prefix;
    $request = db_query("
			SELECT *
			FROM {$db_prefix}eve_corporations
			WHERE EVE_ALLIANCE_ID = '{$alid}'", __FILE__, __LINE__);
    $result = array();
    while($row = mysql_fetch_assoc($request)) {
       $result[] = $row;
    }
	mysql_free_result($request);
    return $result;
}

function getCorporationName($id) {
    global $db_prefix;
    $request = db_query("
			SELECT EVE_NAME
			FROM {$db_prefix}eve_corporations
			WHERE EVE_ID = '{$id}'", __FILE__, __LINE__);
    $result = null;
    if (mysql_num_rows($request) > 0) {
        $row = mysql_fetch_assoc($request);
        $result = $row['EVE_NAME'];
    }
	mysql_free_result($request);
    return $result;
}

function getAllCorporations() {
    global $db_prefix;
    $request = db_query("
			SELECT *
			FROM {$db_prefix}eve_corporations ORDER BY eve_alliance_id", __FILE__, __LINE__);
    $result = array();
    while($row = mysql_fetch_assoc($request)) {
       $result[] = $row;
    }
	mysql_free_result($request);
    return $result;
}

function getCorpAlliance($corpid) {
    global $db_prefix;
    $request = db_query("
			SELECT EVE_ALLIANCE_ID
			FROM {$db_prefix}eve_corporations
			WHERE EVE_ID = '{$corpid}'", __FILE__, __LINE__);
    $result = null;
    if (mysql_num_rows($request) > 0) {
        $row = mysql_fetch_assoc($request);
        $result = $row['EVE_ALLIANCE_ID'];
    }
	mysql_free_result($request);
    return $result;
}

function getAllianceName($id) {
    global $db_prefix;
    if($id == null) return null;
    $request = db_query("
			SELECT EVE_NAME
			FROM {$db_prefix}eve_alliances
			WHERE EVE_ID = '{$id}'", __FILE__, __LINE__);
    $result = null;
    if (mysql_num_rows($request) > 0) {
        $row = mysql_fetch_assoc($request);
        $result = $row['EVE_NAME'];
    }
	mysql_free_result($request);
    return $result;
}

// Alliance EVE data
function fillAllianceData() {
    global $db_prefix;
    db_query("DELETE FROM {$db_prefix}eve_alliances", __FILE__, __LINE__);
    $ea = new EveApi();
    $data = $ea->getAllianceList();
    $xml = new SimpleXMLElement($data);
    $output = array();
    foreach ($xml->result->rowset->row as $row) {
        $index = count($output);
        foreach ($row->attributes() as $key => $val) {
            $output[$index][(string) $key] = mysql_real_escape_string((string) $val);
		}
	}
    foreach ($output as $ad) {
        db_query("INSERT INTO {$db_prefix}eve_alliances (EVE_ID, EVE_NAME) VALUES
        ('{$ad['allianceID']}','{$ad['name']}')", __FILE__, __LINE__);
    }
}

function getAlliances() {
    global $db_prefix;
    $request = db_query("SELECT * FROM {$db_prefix}eve_alliances ORDER BY EVE_NAME", __FILE__, __LINE__);
    $result = array();
    while($row = mysql_fetch_assoc($request)) {
       $result[] = $row;
    }
	mysql_free_result($request);
    return $result;
}

// Rules
function getEveRules() {
    global $db_prefix;
    $request = db_query("SELECT * FROM {$db_prefix}eve_rules", __FILE__, __LINE__);
    $result = array();
    while($row = mysql_fetch_assoc($request)) {
       $result[] = $row;
    }
	mysql_free_result($request);
    return $result;
}
function addEveRule($group_id, $alliance_id, $corp_id, $role) {
    global $db_prefix;
    db_query("INSERT INTO {$db_prefix}eve_rules (EVE_ROLE, EVE_CORP_ID, EVE_ALLIANCE_ID, ID_GROUP) VALUES
        ('{$role}','{$corp_id}','{$alliance_id}','{$group_id}')", __FILE__, __LINE__);
}
function removeEveRule($id) {
    global $db_prefix;
    db_query("DELETE FROM {$db_prefix}eve_rules WHERE ID_RULE = '{$id}'", __FILE__, __NAME__);
}

// Support functions
function getUserGroups() {
    global $db_prefix;
    $request = db_query("SELECT * FROM {$db_prefix}membergroups", __FILE__, __LINE__);
    $result = array();
    while($row = mysql_fetch_assoc($request)) {
       if($row['ID_GROUP'] == 1) continue;
       $result[] = $row;
    }
	mysql_free_result($request);
    return $result;
}
function getGroupName($id) {
    global $db_prefix;
    $request = db_query("
			SELECT groupName
			FROM {$db_prefix}membergroups
			WHERE ID_GROUP = '{$id}'", __FILE__, __LINE__);
    $result = null;
    if (mysql_num_rows($request) > 0) {
        $row = mysql_fetch_assoc($request);
        $result = $row['groupName'];
    }
	mysql_free_result($request);
    return $result;
}

function addEveMemberToGroup($members, $group, $type = 'auto')
{
	global $db_prefix;

	if (!is_array($members))
		$members = array((int) $members);
	else
	{
		$members = array_unique($members);

		// Make sure all members are integer.
		foreach ($members as $key => $value)
			$members[$key] = (int) $value;
	}
	$group = (int) $group;

	// Some groups just don't like explicitly having members.
	$request = db_query("
		SELECT ID_GROUP
		FROM {$db_prefix}membergroups
		WHERE minPosts != -1", __FILE__, __LINE__);
	$implicitGroups = array(-1, 0, 3);
	while ($row = mysql_fetch_assoc($request))
		$implicitGroups[] = $row['ID_GROUP'];
	mysql_free_result($request);

	// Sorry, you can't join an implicit group.
	if (in_array($group, $implicitGroups) || empty($members))
		return false;

	// Only admins can add admins.
	if ($group == 1 && !allowedTo('admin_forum'))
		return false;

	// Do the actual updates.
	if ($type == 'only_additional')
		db_query("
			UPDATE {$db_prefix}members
			SET additionalGroups = IF(additionalGroups = '', '$group', CONCAT(additionalGroups, ',$group'))
			WHERE ID_MEMBER IN (" . implode(', ', $members) . ")
				AND ID_GROUP != $group
				AND NOT FIND_IN_SET($group, additionalGroups)
			LIMIT " . count($members), __FILE__, __LINE__);
	elseif ($type == 'only_primary' || $type == 'force_primary')
		db_query("
			UPDATE {$db_prefix}members
			SET ID_GROUP = $group
			WHERE ID_MEMBER IN (" . implode(', ', $members) . ")" . ($type == 'force_primary' ? '' : "
				AND ID_GROUP = 0
				AND NOT FIND_IN_SET($group, additionalGroups)") . "
			LIMIT " . count($members), __FILE__, __LINE__);
	elseif ($type == 'auto')
		db_query("
			UPDATE {$db_prefix}members
			SET
				additionalGroups = IF(ID_GROUP = 0, additionalGroups, IF(additionalGroups = '', '$group', CONCAT(additionalGroups, ',$group'))),
				ID_GROUP = IF(ID_GROUP = 0, $group, ID_GROUP)
			WHERE ID_MEMBER IN (" . implode(', ', $members) . ")
				AND ID_GROUP != $group
				AND NOT FIND_IN_SET($group, additionalGroups)
			LIMIT " . count($members), __FILE__, __LINE__);
	// Ack!!?  What happened?
	else
		trigger_error('addMembersToGroup(): Unknown type \'' . $type . '\'', E_USER_WARNING);

	// Update their postgroup statistics.
	updateStats('postgroups', 'ID_MEMBER IN (' . implode(', ', $members) . ')');

	return true;
}

?>
